﻿
namespace TingSLsocket

open System

type ClientJobAgent = JobAgent

[<Sealed>]
type RpcClient(svrendpnt,bufsize,_jobagent: ClientJobAgent)=
    let _tcpclient = new TcpClient(svrendpnt,bufsize)
    let _evtError = new Event<exn>()

    do
        _tcpclient.DataRecvExposeEvt.Add _jobagent.Receive
        _jobagent.ForwardEvt.Add (fun (_,buf) -> _tcpclient.SendAsync(buf,0,buf.Length))
        _jobagent.ErrorEvt.Add (fun (_,ex) -> _evtError.Trigger ex)

    member this.Connect() =
        _tcpclient.ConnectAsync()

    member this.Request (cmd,parm) =
        _jobagent.Request(cmd,parm)

    member this.Dispose() =
        (_tcpclient :> IDisposable).Dispose()
        (_jobagent :> IDisposable).Dispose()

    [<CLIEvent>]
    member this.ConnectedEvt = _tcpclient.ConnectedEvt

    [<CLIEvent>]
    member this.ClosedEvt = _tcpclient.ClosedEvt

    [<CLIEvent>]
    member this.ErrorEvt = _evtError.Publish

    interface IDisposable with
        member this.Dispose() = this.Dispose()
            
